'''
Created on 23 fevr. 2011

@author: wp803469

    Detecteur : question 2.5.a
    
    J'utilise une variable aTester qui sert a me faire
    sortir d'une serie de BIP continues, lorsque par exemple le BIP est
    trop fort, et l'ecouteur l'entend, alors on re-BIP, ca ne finit jamais.

'''

import alsaaudio, time, audioop, struct
from math import sin,pi

def biip():
    # Channel 1
    frec1=200    #Frequency
    vol1=1        #Volume
    
    #Channel 2    
    frec2=323     #Frequency
    vol2=1        #Volume
    
    #Very basic choice of parameters
    rate = 44100
    period = 44100
    channels = 2
    
    # device initialization
    out = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card='default')
    
    # parameters
    out.setchannels(channels)
    out.setrate(rate)
    out.setformat(alsaaudio.PCM_FORMAT_S32_LE)
    
    out.setperiodsize(period)
    
    # a list with the sinusoidal signals is built
    maxAmp = pow(2,31) - 1
    
    list = []
    i=period
    while(i>0):
        list.append(maxAmp*vol1*sin(frec1*float(i)/rate*2*pi))
        list.append(maxAmp*vol2*sin(frec2*float(i)/rate*2*pi))
        i-=1
    
    # and the list is writen over and over again. Just kill the process to stop.
    s=struct.pack('<'+channels*period*'l',*list)
    #while(1):
    #    out.write(s)
    out.write(s)


def main():
    
    '''
        initialisation --------------------------------------
    '''
    inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK)
    inp.setchannels(1)
    inp.setrate(8000)
    inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    inp.setperiodsize(160)
    
    
    '''
        on ecoute -----------------------------------------
    '''
    pret = True
    while True:
        # Read data from device
        l,data = inp.read()
        if l:
            aTester = audioop.max(data, 2)
            print aTester
            if pret and aTester > 10000:
                pret = False
                print "BIIIIIIP"
                biip()
            else:
                pret = True
        time.sleep(.01)
        
if __name__ == '__main__':
    main()
    
    
    
    
